<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库类别" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择入库类别" clearable>
          <el-option
            v-for="dict in dict.type.asset_in_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资产分类" prop="cate_id">
        <treeselect v-model="queryParams.cate_id" :options="cateOptions" style="width:180px"
          :normalizer="normalizer" placeholder="请选择资产分类" />
      </el-form-item>
      <el-form-item label="资产编号" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="house_id">
        <el-select v-model="queryParams.house_id" placeholder="请选择仓库" clearable>
          <el-option
            v-for="u in houseOptions"
            :key="u.value"
            :label="u.label"
            :value="u.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接收人" prop="user_id">
       <el-select v-model="queryParams.user_id" placeholder="请选择接收人" filterable clearable>
          <el-option
            v-for="u in userOptions"
            :key="u.value"
            :label="u.label"
            :value="u.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接收时间" prop="recv_time">
       <el-date-picker
          v-model="queryParams.recv_time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd1"
          v-hasPermi="['asset:in:add']"
        >采购入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd2"
          v-hasPermi="['asset:in:add']"
        >归还入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:in:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库类别" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.asset_in_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="资产分类" align="center" prop="cate_name" />
      <el-table-column label="资产型号" align="center" prop="model_name" />
      <el-table-column label="资产编码" align="center" prop="asset_num" />
      <el-table-column label="仓库" align="center" prop="house_name" />
      <el-table-column label="入库说明" align="center" prop="remark" />
      <el-table-column label="接收人" align="center" prop="user_name" />
      <el-table-column label="接收时间" align="center" prop="recv_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recv_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据图片" align="center" prop="imgs" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imgs" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['asset:in:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />
    <!-- 添加或修改入库记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="form.type == '1'">
        <el-form-item label="资产编号" prop="asset_num">
          <el-input v-model="form.asset_num" placeholder="请输入资产编号"/>
        </el-form-item>
        <el-form-item label="订购单" prop="purchase_id">
          <el-select v-model="form.purchase_id" placeholder="请选择订购单" clearable>
            <el-option
                v-for="v in purchaseOptions"
                :key="v.id"
                :label="v.dept_name + '-' + v.user_name + ' 采购 ' + v.model_name + '(' + v.amount+v.unit+')'"
                :value="v.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="house_id">
          <el-select v-model="form.house_id" placeholder="请选择仓库" clearable>
            <el-option
                v-for="u in houseOptions"
                :key="u.value"
                :label="u.label"
                :value="u.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入入库说明" />
        </el-form-item>
        <el-form-item label="收货单" prop="imgs">
          <image-upload v-model="form.imgs"/>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="form.type == '2'">
        <el-form-item label="资产编号" prop="asset_id">
          <el-select v-model="form.asset_id" placeholder="请选择待归还单" clearable filterable @change="changeUse">
            <el-option
                v-for="v in useOptions"
                :key="v.asset_id"
                :label="v.cate_name + ' ' + v.model_name + ' ' + v.num "
                :value="v.asset_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资产分类" prop="cate_name">
          <el-input v-model="form.cate_name" placeholder="请输入资产编号" readonly/>
        </el-form-item>
        <el-form-item label="型号" prop="model_name" >
          <el-input v-model="form.model_name" placeholder="请输入资产编号" readonly/>
        </el-form-item>
        <el-form-item label="仓库" prop="house_id">
          <el-select v-model="form.house_id" placeholder="请选择仓库" clearable>
            <el-option
                v-for="u in houseOptions"
                :key="u.value"
                :label="u.label"
                :value="u.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入入库说明" />
        </el-form-item>
        <el-form-item label="确认单" prop="imgs">
          <image-upload v-model="form.imgs"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <import-dialog :open="upload" model="asset_in" @cancel="importCancel" @success="importSuccess" />
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiDelete, apiPatch, apiDs, apiExport, apiDownload } from "@/api/openapi";
import ImportDialog from "@/components/ImportDialog";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "In",
  components: {
    Treeselect, ImportDialog
  },
  dicts: ['asset_in_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库记录表格数据
      inList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        type: null,
        cate_id: null,
        asset_id: null,
        house_id: null,
        user_id: null,
        recv_time: [],
        num: null,
        "@alias": "t",
        "@exp": {
          recv_time: 'bt',
          num: 'lk'
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "id desc",
      },
      // 导入参数
      upload: false,
      // 表单参数
      form: {},
      assetOptions: [],
      houseOptions: [],
      cateOptions: [],
      modelOptions: [],
      userOptions: [],
      purchaseOptions: [],
      useOptions: [],
      // 表单校验
      rules: {
        asset_num: [
          { required: true, message: "资产编号不能为空", trigger: "blur" }
        ],
        purchase_id: [
          { required: true, message: "采购单不能为空", trigger: "blur" }
        ],
        house_id: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    apiDs('asset_house_select').then(response=>{
        this.houseOptions = response.data;
    });
    apiDs('asset_model_select').then(response=>{
        this.modelOptions = response.data;
    });
    apiDs('asset_category_select').then(response=>{
        this.cateOptions = this.handleTree(response.data, "value", "pid");
    });
    apiDs('sys_user_select').then(response=>{
        this.userOptions = response.data;
    });
  },
  computed: {
    formModelOptions: function () {
      let options = [];
      if(this.form.cate_id == null){
        return options;
      }
      for(var i=0;i<this.modelOptions.length;i++){
        if(this.modelOptions[i].cate_id == this.form.cate_id){
          options.push(this.modelOptions[i]);
        }
      }
      console.log(options)
      return options;
    },    
    searchModelOptions: function () {
      let options = [];
      if(this.form.cate_id == null){
        return options;
      }
      for(var i=0;i<this.modelOptions.length;i++){
        if(this.modelOptions[i].cate_id == this.queryParams.cate_id){
          options.push(this.modelOptions[i]);
        }
      }
      return options;
    }
  },
  methods: {
    /** 查询入库记录列表 */
    getList() {
      this.loading = true;
      let params = {};
      params['asset_in'] = {...this.queryParams};
      if(this.queryParams.recv_time.length == 0){
        params['asset_in']['recv_time'] = null;
      }
      params['asset_warehouse'] = {
          "@alias": "w",
          "@join": "w.id = t.house_id",
          "@column":"name:house_name"
      };
      params['sys_user'] = {
          "@alias": "u",
          "@join": "LEFT u.user_id = t.user_id",
          "@column":"nick_name user_name"
      };
      params['@pager'] = this.pager;
      apiGet(params).then(response => {
        this.inList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 转换资产分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        type: null,
        asset_num: null,
        purchase_id: null,
        cate_id: null,
        cate_name: null,
        mode_id: null,
        model_name: null,
        asset_id: null,
        price: null,
        house_id: null,
        remark: null,
        user_id: "@userId()",
        recv_time: "@now()",
        imgs: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd1() {
      this.reset();
      this.form.type = '1';
      this.open = true;
      this.title = "采购入库";

      let data = { asset_purchase:{
            "@column": "*",
            "@alias": "t",
            "check_status":"2",
            "apply_status":"2,3",
            "@exp":{"apply_status":"in"}
        },
        asset_model:{
            "@column": "name:model_name,unit,price:model_price",
            "@alias": "m",
            "@join":"m.id = t.model_id"
        },
        asset_category:{
            "@column": "name:cate_name",
            "@alias": "c",
            "@join":"c.id = m.cate_id"
        },
          "@pager":{limit:1000}
      };
      apiGet(data).then(response => {
        this.purchaseOptions = response.data.rows;
      });
    },
    /** 新增按钮操作 */
    handleAdd2() {
      this.reset();
      this.form.type = '2';
      this.open = true;
      this.title = "归还入库";

      let data = { asset_use_detail:{
            "@column": "*",
            "@alias": "t",
            "in_time":"1",
            "@exp":{"in_time":"null"}
        },
        asset_info:{
            "@column": "num,house_id",
            "@alias": "i",
            "@join":"i.id = t.asset_id"
        },
        asset_model:{
            "@column": "name:model_name",
            "@alias": "m",
            "@join":"m.id = i.model_id"
        },
        asset_category:{
            "@column": "name:cate_name",
            "@alias": "c",
            "@join":"c.id = m.cate_id"
        },
          "@pager":{limit:1000}
      };
      apiGet(data).then(response => {
        this.useOptions = response.data.rows;
      });
    },
    changeUse() {
      for(var i=0;i<this.useOptions.length;i++){
        if(this.useOptions[i].asset_id == this.form.asset_id){
          this.form.asset_num = this.useOptions[i].num;
          this.form.cate_id = this.useOptions[i].cate_id;
          this.form.model_id = this.useOptions[i].model_id;
          this.form.model_name = this.useOptions[i].model_name;
          this.form.cate_name = this.useOptions[i].cate_name;
          this.form.house_id = this.useOptions[i].house_id;
        }    
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      let data = {};
       data['asset_in'] = { id:id};
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {            
            if(this.form.type == '1'){
               this.enterPurchase();
            }else if(this.form.type == '2'){
              let data = {'@tags':['asset_in']};
              data['asset_in'] = this.form;
              apiPatch(data).then(response => {
                this.$modal.msgSuccess("入库成功");
                this.open = false;
                this.getList();
              });
            }else{
                //未知
                this.$modal.msgError("未知操作");
                return;
            }            
        }
      });
    },
    enterPurchase(){      
      let data = {};
      data['asset_in'] = this.form;
      data['@tags'] = ['asset_info', 'asset_in'];
      var purchase = null;
      for(var i=0;i<this.purchaseOptions.length;i++){
          if(this.form.purchase_id == this.purchaseOptions[i].id){
            purchase = this.purchaseOptions[i];              
          }
      }
      data['asset_in']['asset_id'] = "@asset_info.id";
      data['asset_in']['model_name'] = purchase.model_name;
      data['asset_in']['cate_name'] = purchase.cate_name;
      data['asset_in']['dept_id'] = purchase.dept_id;
      data['asset_in']['user_id'] = purchase.user_id;


      //设备明细
      data['asset_info'] ={
          model_id: purchase.model_id,
          house_id:this.form.house_id,
          dept_id: purchase.dept_id,
          purchase_id: purchase.id,
          num: this.form.asset_num.trim(),
          price: purchase.model_price,
          buy_time: "@now()",
          status:'1'
      };
      apiPatch(data).then(response => {
        this.$modal.msgSuccess("入库成功");
        this.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的入库记录数据？').then(function() {
        let data = {};
        data['asset_in'] = { id:ids, "@exp":{id:"in"}};
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload = true;
    },
    importSuccess(msg) {
        this.upload = false;
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    importCancel() {
        this.upload = false;
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['asset_in'] = {...this.queryParams};
      if(this.queryParams.recv_time.length == 0){
        params['asset_in']['recv_time'] = null;
      }
      params['@pager'] = {page:1, limit:10000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    }
  }
};
</script>